<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class customer extends CI_Controller {
	var $data;
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('pagination');
		$this->load->library('fclass');
		$data['title'] = "Customer";
		$this->load->model('model_customer');
		$this->load->model('model_user');
		$this->load->model('model_feeds');
		$this->load->model('model_companies');
		$this->load->model('model_history');
			$this->load->model('model_conflict');
		
		// CHECK LOGIN
		$check = $this->session->userdata('login');
		if($check==false){
		//	print_r($_SERVER["REQUEST_URI"]);
		//return;
			redirect(base_url().'login/?'.$_SERVER["QUERY_STRING"]."&rederect=".$_SERVER["REQUEST_URI"], 'refresh');
			return;
		}


	//	$class = $this->uri->rsegments;
		//if($this->fclass->check_permission('special','is_sale',$this->session->userdata('permissions2'),$this->session->userdata('permissions_base'))){

			//return;
		//}
	}

	public function index()
	{
		$this->load->view('customer', $this->data);
	}

	public function detail(){
		if(isset($_REQUEST['id'])&&$_REQUEST['id']!=""){

			$mod = @$_REQUEST["mod"];
			if($mod=="verify"){
				$this->model_customer->update(array("cust_status"=>1),$_REQUEST["id"]);
			}

			$array_parent_id =$this->session->userdata('parentId');
			
			$per = $this->session->userdata('user_info');
			$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];			
			if(isset($my_permisstion["user_type"]["is_account"])){
				$array_parent_id=array();
			}
			
			$cust_id=$_REQUEST['id'];
			$result_cust = $this->model_customer->selectDetail(array("cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'cust_id'=>$cust_id));
			if(count($result_cust)>0){
				$this->data["result"]=$result_cust[0];

				//$array=array();
				// SET HIDE DATA
			//	$hideArray=$this->session->userdata('per_view');
			//print_r($my_permisstion["customer"]);
			if(isset($my_permisstion["customer"])){
				foreach($my_permisstion["customer"] as $keys =>$val){		
					if(strlen($keys)>4&&substr($keys,0,4)=="hide"){
						//echo str_replace("hide","",$keys);
						//if(trim($this->data["result"][$vl])!=""){
							$this->data["result"][str_replace("hide_","",$keys)]="********";
							//$this->data["result"][$vl] = $this->fclass->subStringVN($this->data["result"][$vl],4)."...........";
					//	}				
					}				
				}
			}


				$result = $this->model_companies->selectToCustID(array('cust_id'=>$cust_id));
				$this->data["result_comp"]=$result;

				//$resultConflict = $this->model_user->selectSaleConflict(array('cust_id'=>$cust_id,'cust_conflict_id'=>$cust_id,"uId"=>$this->session->userdata('uId')));
			//	$this->data["result_conflict"] = $resultConflict;

				$paging=@$_GET["per_page"];
				if($paging<0){
					$paging=0;
				}

				//$where = $this->input->post('where');
				//$resultListSale = $this->model_user->selectParent(array("rId"=>$this->session->userdata('rId'),'uStatus'=>1,'where'=>$where,'order_by'=>'uFullname ASC','limit'=>10,'paging'=>$paging));
				//$this->data["result_listSale"] = $resultListSale;


				//$resultListSaleCount = $this->model_user->selectParentCount(array("rId"=>$this->session->userdata('rId'),'uStatus'=>1,'where'=>$where));
				//$this->data["result_listSale_count"] = $resultListSaleCount;


				$this->data["feed_result"] = $this->model_feeds->select(array('cust_id'=>$cust_id,"limit"=>10,"paging"=>$paging));
				$this->data["feed_count_page"] = $this->model_feeds->selectCount(array('cust_id'=>$cust_id));

				//$result = $this->model_user->selectDetailId(array('uId'=>$this->data["feed_result"]["feed_creator_id"]));
				//$this->data["result_user"]=$result;


				$this->data["set_page"] 	= 'customer_detail';
				$this->load->view('qt/customer_detail', $this->data);
			}else{
				$this->load->view('404');
			}
		}else{
			$this->load->view('404');
		}

	}



	public function add(){
		$result = $this->model_customer->finance_line_select();		
		$this->data["result"] = $result;
		//$this->data["set_page"] = 'customer_add';
		//$this->load->view('customer', $this->data);
        
        $this->load->view('qt/customer_add',$this->data);
	}

	public function add_form(){
		$result = $this->model_customer->finance_line_select();
		$this->data["result"] = $result;
		$this->load->view('qt/customer_add1');
	}

	public function insert(){
		if($_SERVER['REQUEST_METHOD'] == 'POST'){ // if 1
			$array=array();
			if(trim($_POST["cust_last_name"])==""||trim($_POST["cust_phone"])==""||trim($_POST["cust_email"])==""){
				$array=array("st"=>0,"msg"=>"Vui lòng nhập đầy đủ thông tin");
			}else{ // if 2

				$result=$this->model_customer->checkExists(
					array('cust_email'	=>$_POST["cust_email"],
						'cust_cmnd'		=>$_POST["cust_cmnd"],
						'cust_phone'	=>$_POST["cust_phone"],
						'cust_tax_code'	=>$_POST["cust_tax_code"],
						"cust_creator_id"=>$this->session->userdata('uId')
						)
					);

				if(count($result)>0){
					$array = array("st"=>-1,"msg"=>"Khách hàng cá nhân này đã tồn tại trong danh sách khách hàng của bạn");
				}else{ // if 3
					$result = $this->model_customer->checkExists(array('cust_cmnd'=>$_POST["cust_cmnd"],'cust_email'=>$_POST["cust_email"],'cust_phone'=>$_POST["cust_phone"],'cust_tax_code'=>$_POST["cust_tax_code"]));		
					$id_conflict = $this->idConflict($result);

					
					if($_POST["cust_dob"]==""){
						$_POST["cust_dob"]=date('d-m-Y',time());
					}

					$arrayCust = array(
						'cust_tax_code'	=>$_POST["cust_tax_code"],
						'cust_name'			=> '',
						'cust_first_name'	=> $_POST["cust_first_name"],
						'cust_last_name'	=> $_POST["cust_last_name"],
						'cust_address'		=> $_POST["cust_address"],
						'cust_phone'		=> $_POST["cust_phone"],
						'cust_email'		=> $_POST["cust_email"],
						'cust_cmnd'			=> $_POST["cust_cmnd"],
						'cust_cmnd_date'	=> $_POST["cust_cmnd_date"],
						'cust_sex'			=> $_POST["cust_sex"],
						'cust_bank_account'	=> $_POST["cust_bank_account"],
						'cust_status'		=> 0,
						'cust_creator_id'	=> $this->session->userdata('uId'),
						'cust_create_time'	=> time(),
						'cust_dob'			=> $_POST["cust_dob"]
						//,
					//	'line_id'			=> json_encode($_POST["finance_lines"])
						);

					$arrayComp=array(
						'comp_name'			=> $_POST["cust_first_name"]." ".$_POST["cust_last_name"],
						'comp_address'		=> $_POST["cust_address"],
						'comp_phone'		=> $_POST["cust_phone"],
						'comp_ceo_name'		=> '',
						'comp_tax_code'		=> $_POST["cust_tax_code"],
						'comp_bank_account'	=> $_POST["cust_bank_account"],
						'comp_create_time'	=> time(),
						'comp_status'		=> 0,
						'comp_type'			=> 0
						);

					$cust_id = $this->model_customer->insert(array("arrayCust" => $arrayCust));
					$comp_id = $this->model_companies->insert(array("arrayComp" => $arrayComp));

					$this->model_customer->insertCustUser(array("cust_id"=>$cust_id,"uId"=>$this->session->userdata('uId')));
					$this->model_customer->insertCompCust(array("cust_id" => $cust_id,"comp_id" => $comp_id));
					/*
					if(count($result)>0){
						$conflict_id  = "";
						$checkExists = false;
						$creat_id ="";
						foreach($result as $number => $value ){
							$conflict_id = $value["cust_id"];
							$checkExists = true;
							$creat_id =$value["cust_creator_id"];
							*/
							/*
							if($value["line_id"]!=""){
								$dt = json_decode($value["line_id"],true);
								if(count($dt)>0){
									foreach($dt as $vl){
										if(in_array($vl, $_POST["finance_lines"])){
											$checkExists=true;
										}
									}
								}
							}
							*/
							/*
							$res_per = $this->model_user->selectPermitionApp(array("user_id"=>$creat_id));
							$permissions = json_decode($res_per["permissions"],true);
							$this_permissions = $this->session->userdata('permission_apps');
							if(count($this_permiton)>0){
								foreach($permissions["business"] as $key1 => $val){
									foreach($this_permissions["business"] as $key2 => $val){
										if()
									}
								}
							}						
						}
						*/



						if($id_conflict!=""){
							$this->model_customer->update(array("cust_status"=>-2,"cust_conflict_id"=>$id_conflict),$cust_id);
							//$this->model_customer->updateCustUser(array("status"=>0),$custUserId);							
							$array=array("st"=>0,"msg"=>"Thêm thành công (Người dùng này đã có trong hệ thống, vui lòng liên hệ supper sale giải quyết)");	
						}else{
							$array=array("st"=>1,"msg"=>"Thêm thành công","cust_id"=>$cust_id);
						}
						
				//	}else{ 
					//	$array=array("st"=>1,"msg"=>"Thêm thành công","cust_id"=>$cust_id);
				//	}
				} // if 3

			}// if 2
			echo json_encode($array);
		}// if 1
	}


	public function idConflict($result){
		//print_r($result);
		if(count($result)>0){
			foreach ($result as $key => $value) {
				$rows =	$this->model_customer->selectIdConflict(array("cust_id"=>$value["cust_conflict_id"]));
				if(count($rows)>0){
					if(trim($rows[0]["cust_conflict_id"])==""){
						return $rows[0]["cust_id"];
						break;
					}else{
						$this->idConflict($rows);
					}
				}else{
					return $value["cust_id"];
					break;
				}
			}	
		}else{
			return "";
		}
		
	}

	public function update(){
		$name_col	= $_REQUEST["name"];
		$value		= $_REQUEST["value"];
		$id			= $_REQUEST["id"];
		if(trim($name_col)==""){
			echo json_encode(array("result"=>false,"msg"=>"HACKING ERROR"));
		}else if(trim($value)==""){
			echo json_encode(array("result"=>false,"msg"=>"Vui lòng nhập nội dung"));
		}else if(trim($id)==""){
			echo json_encode(array("result"=>false,"msg"=>"Không tìm thấy ID"));
		}else{
			$this->model_customer->update(array($name_col=>$value,'cust_status'=>0),$id);
			echo json_encode(array("result"=>true,"msg"=>$value));
		}
	}


	public function move_customer(){
		$array=array();
		$uId		= $_REQUEST["uId"];
		$cust_id	= $_REQUEST["cust_id"];
		$cust_conflict_id = $_REQUEST["cust_conflict_id"];
		// Cap nhan user qua 
		$this->model_customer->update(array('cust_creator_id'=>$uId),$cust_id);
		// REMOVE customer conflict
		$this->model_customer->delete(array('cust_id'=>$cust_conflict_id));
		// LAAY DANH SACH CTY BANG TRUNG GIAN
		$ressult = $this->model_customer->selectCompCust(array('cust_id'=>$cust_conflict_id));
		// REMOVE DANH SACH BANG TRUNG GIAN
		$this->model_customer->deleteCompCust(array('cust_id'=>$cust_conflict_id));

		$this->model_feeds->updateCustID(array('feed_cust_id'=>$cust_id),$cust_conflict_id,$uId);
		// Khi Ke Toan Xóa Công Ty thì khách hàng sẽ được duyển qua cty khác, nhưng khách hàng này bị trùng, khi đó sale xóa khách hàng sẽ bị xoóa luôn cty mới
		//foreach($ressult as $value){
		//	$this->model_companies->delete(array('comp_id'=>$value["comp_id"]));//$array[]=$value["comp_id"];
		//}

		echo json_encode(array("result"=>true,"msg"=>"Chuyển sale thành công"));
	}

	public function remove_customer(){
		$array=array();
		$cust_conflict_id = $_REQUEST["cust_conflict_id"];
		$this->model_customer->delete(array('cust_id'=>$cust_conflict_id));
		// LAAY DANH SACH CTY BANG TRUNG GIAN
		$ressult = $this->model_customer->selectCompCust(array('cust_id'=>$cust_conflict_id));
		// REMOVE DANH SACH BANG TRUNG GIAN
		$this->model_customer->deleteCompCust(array('cust_id'=>$cust_conflict_id));
		foreach($ressult as $value){
			$this->model_companies->delete(array('comp_id'=>$value["comp_id"]));//$array[]=$value["comp_id"];
		}

		//$this->model_feeds->deleteCustID(array('feed_cust_id'=>$cust_conflict_id,'feed_creator_id'=>));
		echo json_encode(array("result"=>true,"msg"=>"Loại bỏ sale conflict thàn công"));
	}

	public function update_sale(){
		$cust_id = $_REQUEST["cust_id"];
		$uId	 = $_REQUEST["uId"];
		$this->model_customer->update(array('cust_creator_id'=>$uId),$cust_id);
		echo json_encode(array("result"=>true,"msg"=>"Thay đổi sale thành công"));
	}

	public function create_acc(){
		$cust_id = $_REQUEST["cust_id"];
		if(trim($cust_id)!=""){
			$result = $this->model_customer->selectIdDetail(array("cust_id"=>$cust_id));
			if(count($result)>0){
				$account=$result["cust_phone"];
				$this->model_customer->update(array("cust_username"=>$account,"cust_password"=>md5("123456")),$cust_id);
				echo json_encode(array("result"=>true,"msg"=>"Tạo tài khoản thành công."));
			}else{
				echo json_encode(array("result"=>false,"msg"=>"Không tìm thấy khách hàng này"));
			}
		}else{
			echo json_encode(array("result"=>false,"msg"=>"ID NULL"));
		}
	}

	public function remove_img_cmnd(){
		if(isset($_REQUEST['id']) && isset($_REQUEST['key'])){

			$result = $this->model_customer->selectIdDetail(array("cust_id"=>$_REQUEST['id']));
			//$customer = mysql_fetch_assoc($result);
			$comp_images = json_decode($result['cust_cmnd_images'],true);
			unset($comp_images[$_REQUEST['key']]);

			$data = array();
			//$data['comp_id'] = $_REQUEST['id'];
			$data['cust_cmnd_images'] = json_encode($comp_images);

			$result = $this->model_customer->update($data,$_REQUEST['id']);

			echo json_encode(array('result' => true,"msg"=>"xóa hình thành công"));
		}
		else echo json_encode(array('result' => false,"msg"=>"xóa hình thất bại"));
	}


	public function get_list_wall(){
		if(isset($_REQUEST["s"])){
			$fix = array();
			$result = $this->model_customer->select1(array('join_tbl_cust_users'=>'','uId'=>$this->session->userdata('uId'),'where'=>$_REQUEST["s"],'order_by'=>'cust_name ASC',"limit"=>6,"paging"=>0));
		//	echo $this->db->last_query();
			$array =array();
			foreach($result as $value){
				$_fix_check =false;

				$my_permisstion =  $this->session->userdata('permission_apps');
			
				$actionHtml ='<li><a href="javascript:postFeeds(1)"><i class="fa fa-sign-in"></i> Đăng</a></li>
								<li><a href="javascript:postFeeds(2)"><i class="fa fa-share"></i> Đăng &amp; Tạo Công Việc</a></li>';
		
				$prefix_result = $this->model_conflict->selectCustUserFull(array("cust_id"=>$value["cust_id"]));
			
				//print_r($prefix_result);
				foreach($prefix_result as $fix_value){

					if($fix_value["line_prefix"]!=""&&$fix_value["line_prefix"]!="[]"&&$fix_value["line_prefix"]!="null"){
						$fix = json_decode($fix_value["line_prefix"],true);	

						if(count($fix)>0){						
						//foreach($fix as $f_val){
							if(in_array("LED", $fix)==true&&$fix_value["uId"]!=$this->session->userdata('uId')){
								$_fix_check =true;
							}
						//}
						}
						//echo $fix_value["line_prefix"];					
					}
					
					
					
				}

			if($_fix_check!=true){
			//print_r($this->session->userdata('user_info'));
			$per = $this->session->userdata('user_info');
			//print_r($per);
			$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];
				if(isset($my_permisstion["user_line"])&&count($my_permisstion)>0&&$my_permisstion!=""){
					foreach($my_permisstion["user_line"] as $key => $v){
						if(strtoupper($key)=="LED"&&$v==1){							
							$actionHtml.='<li><a href="javascript:postFeeds(3)"><i class="fa fa-ticket"></i> Đăng &amp; Book Lịch LED</a></li>';															
						}
					}
				}
			}

			$actionHtml.='<li><a href="javascript:load_project_form()"><i class="fa fa-sun-o"></i> Đăng &amp; Tạo Dự Án</a></li>';
			
				$array[]=array(
					"comp_address"=>$value["comp_address"],
					"comp_name"	=>$value["comp_name"],
					"cust_address"=>$value["cust_address"],
					"cust_id"	=>$value["cust_id"],
					"cust_name"	=>$value["cust_sex"].". ".$value["cust_first_name"]." ".$value["cust_last_name"],'html_action'=>$actionHtml);
			}
			echo json_encode($array);
		}
	}

	public function list_sale($paging = 0){
		if($paging<0||$paging==""){
			$paging =0;
		}
		$cust_id = $this->input->post("cust_id");
		$array_us_id = array();
		$table_id = array();
		$array_fix = array();
		$result = $this->model_customer->selectCust(array("cust_id"=>$cust_id));
		foreach($result as $key => $val){
			$array_us_id[]=$val["uId"];
			$table_id[$val["uId"]]=$val["id"];
			$array_fix[$val["uId"]]=$val["line_prefix"];
		}
		

		
		$result = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT");
		$json = json_decode($result,true);
		$list="";
		if($json["result"]==true){
			
			$re_fix = "";
			$color = array('info','danger','success','dark','dark','dark','dark','dark','dark','dark');
			foreach($json["users"] as $key => $value){
			$re_fix = "";
				if(in_array($value["user_id"],$array_us_id)){
				   if($array_fix[$value["user_id"]]!=""&&$array_fix[$value["user_id"]]!="[]"&&$array_fix[$value["user_id"]]!="null"){
						$prefix = json_decode($array_fix[$value["user_id"]],true);
					//	print_r($prefix);
						foreach ($prefix as $k => $v){
							$re_fix.='<span class="badge bg-'.$color[$k].'">'.$v.'</span> ';
						}
					}
					$list .= '<tr>
								<td><label class="checkbox m-n i-checks"><input type="checkbox" value="'.$table_id[$value["user_id"]].'" name="check_cust_user"><i></i></label></td>						
								<td class="text-left">'.$value["user_fullname"].'</td>
								<td class="text-left">'.@$value["user_phone"].'</td>
								<td class="text-left">'.$re_fix.' </td>
								<td class="text-left"><a href="'.base_url('customer/edit_sale_fix?id=').$value["user_id"].'&cust_id='.$cust_id.'" data-toggle="ajaxModal"><i class="fa fa-edit"></i> sửa</a></td>
							</tr>';
						}
			}
		}
		
		
		
		/*
		$array_rpaent_id =explode("|", $this->session->userdata('parentId'));
		$cust_id = $this->input->post("cust_id");
		$where = $this->input->post("where");
		
		$result = $this->model_customer->selectSale(array("cust_id"=>$cust_id,"array_uId"=>$array_parent_id,"limit"=>10,"paging"=>$paging,"where"=>$where));

		$list = "";

		foreach($result as $key => $value){
			$prefix = array();
			$re_fix = "";
			$color = array('info','danger','success','dark ');
			if($value["line_prefix"]!=""&&$value["line_prefix"]!="[]"&&$value["line_prefix"]!="null"){
				$prefix = json_decode($value["line_prefix"],true);
				if(count($prefix)>0){
					foreach ($prefix as $key => $val){
						$re_fix.='<span class="badge bg-'.$color[$key].'">'.$val.'</span> ';
					}
		
				}
			}
			
			
			
			
			
			$list .= '<tr>
						<td><label class="checkbox m-n i-checks"><input type="checkbox" value="'.$value["id"].'" name="check_cust_user"><i></i></label></td>						
						<td class="text-left">'.$value["uFullname"].'</td>
						<td class="text-left">'.$value["uPhone"].'</td>
						<td class="text-left">'.$re_fix.'</td>
						<td class="text-left"><a href="'.base_url('customer/edit_sale_fix?id=').$value["uId"].'&cust_id='.$cust_id.'" data-toggle="ajaxModal"><i class="fa fa-edit"></i> sửa</a></td>
					</tr>';
		}

		$result = $this->model_customer->selectSale(array("cust_id"=>$cust_id,"array_uId"=>$array_parent_id,"where"=>$where));

		$config['base_url'] = 'javascript:;" data-url="'.base_url('customer/list_sale').'';
		$config['total_rows'] = count($result);
		$config['per_page'] = 10; 
		$config['full_tag_open'] = '<li>';
		$config['full_tag_close'] = '</li>';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		$config['cur_tag_open'] = '<li><a><b>';
		$config['cur_tag_close'] = '</b></a></li>';
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$this->pagination->initialize($config); 
	*/
		echo json_encode(array("st"=>1,"msg"=>$list,'page'=>$this->pagination->create_links()));
	}

	public function full_sale_view(){
		$this->load->view("customer_full_sale_view");
	}

	public function list_full_sale($paging = 0){
	/*
		if($paging<0||$paging==""){
			$paging =0;
		}

		$array_parent_id =explode("|", $this->session->userdata('parentId'));
		$cust_id = $this->input->post("cust_id");
		$where = $this->input->post("where");
		
		$result = $this->model_customer->selectFullSale(array("array_uId"=>$array_parent_id,"limit"=>10,"paging"=>$paging,"where"=>$where));

		//print_r($result);

		$list = "";

		foreach($result as $key => $value){
			$list .= '<tr>
						<td><label class="checkbox m-n i-checks"><input type="checkbox" value="'.$value["uId"].'" name="check_user_id"><i></i></label></td>						
						<td class="text-left">'.$value["uFullname"].'</td>
						<td class="text-left">'.$value["uPhone"].'</td>
					</tr>';
		}

		$result = $this->model_customer->selectFullSale(array("array_uId"=>$array_parent_id,"where"=>$where));

		$config['base_url'] = 'javascript:;" data-url="'.base_url('customer/list_full_sale').'';
		$config['total_rows'] = count($result);
		$config['per_page'] = 10; 
		$config['full_tag_open'] = '<li>';
		$config['full_tag_close'] = '</li>';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		$config['cur_tag_open'] = '<li><a><b>';
		$config['cur_tag_close'] = '</b></a></li>';
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$this->pagination->initialize($config); 
		
		echo json_encode(array("st"=>1,"msg"=>$list,'page'=>$this->pagination->create_links()));
		*/
		
		$result = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT");
	//	echo "http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT";
		
		$json = json_decode($result,true);
		//print_r($json);
		$list="";
		if($json["result"]==true){
			
			if($this->session->userdata('parentId')!=""&&count($this->session->userdata('parentId'))>0){
				foreach($json["users"] as $key => $value){
					if(in_array($value["user_id"],$this->session->userdata('parentId'))){
						$list .= '<tr>
									<td><label class="checkbox m-n i-checks"><input type="checkbox" value="'.$value["user_id"].'" name="check_user_id"><i></i></label></td>						
									<td class="text-left">'.$value["user_fullname"].'</td>
									<td class="text-left">'.@$value["user_phone"].'</td>
								</tr>';
							}
				}
			}
		}
		echo json_encode(array("st"=>1,"msg"=>$list,"page"=>''));
		//print_r($result);
	}


	public function remove_sale(){		
		$id = $this->input->post("id");
		$cust_id = $this->input->post("cust_id");
		foreach($id as $key => $value){
			$this->model_customer->deleteCustUser(array("id"=>$value));
			$this->model_history->insert(array("his_action"=>"Loại bỏ sale ra khỏi khách hàng","his_create_date"=>time(),"hist_desc"=>"","user_active_id"=>$this->session->userdata('uId'),"user_id"=>$value,"cust_id"=>$cust_id,"his_type"=>1));
		}	
		echo json_encode(array("st"=>1,"msg"=>"Xóa thành công"));		
	}

	public function add_sale(){		
		$id = $this->input->post("id");
		$cust_id = $this->input->post("cust_id");
		foreach($id as $key => $value){
			$row_num = $this->model_customer->checkCustUserExists(array("cust_id"=>$cust_id,"uId"=>$value));
			if($row_num<=0){
				$this->model_customer->insertCustUser(array("cust_id"=>$cust_id,"uId"=>$value));
			$this->model_history->insert(array("his_action"=>"Thêm Sale vào khách hàng","his_create_date"=>time(),"hist_desc"=>"","user_active_id"=>$this->session->userdata('uId'),"user_id"=>$value,"cust_id"=>$cust_id,"his_type"=>2));
			}			
		}	
		echo json_encode(array("st"=>1,"msg"=>"Thêm thành công"));		
	}


	public function edit_sale_fix(){

		$cust_id = $this->input->get("cust_id");
		$uId 	= $this->input->get("id");
		$result =  $this->model_conflict->selectCustUser(array("cust_id"=>$cust_id,"uId"=>$uId));
		$this->data["refix"] = json_decode($result["line_prefix"],true);

		$result = $this->model_customer->selectFinanceLines();
	//	print_r($result);
		$this->data["result"] = $result;
		$this->load->view("customer_edit_sale_fix",$this->data);
	}

	public function add_sale_fix(){
		$cust_id = $this->input->post("cust_id");		
		$user_id = $this->input->post("user_id");
		$line_id = $this->input->post("line_id");
		if($cust_id==""||$user_id==""||$line_id==""){
			echo json_encode(array("st"=>0,"msg"=>"Thiếu thông tin"));	
			return;
		}

		$array = array();

		foreach ($line_id as $key => $value) {
			array_push($array,$value);
		}
		//print_r($line_id);
		$ar = array();
		// Loại bỏ hết type
		$result = $this->model_conflict->selectCustUserFull(array("cust_id"=>$cust_id));
		foreach ($result as $key => $value) {
			$ar = json_decode($value["line_prefix"],true);
			if(count($ar)>0){
				foreach($ar as $k =>$v){
					if(in_array($v, $line_id)){						
						if($user_id!=$value["uId"]){
							$this->model_history->insert(array("his_action"=>"Hủy bỏ ngành hàng: [".$ar[$k]."]","his_create_date"=>time(),"hist_desc"=>"","user_active_id"=>$this->session->userdata('uId'),"user_id"=>$value["uId"],"cust_id"=>$value["cust_id"],"his_type"=>3));
						}	
						unset($ar[$k]);					
					}
				}
			}
			
			// Update toàn bộ value			
			$this->model_conflict->updateCustUser(array("line_prefix"=>json_encode($ar)),array("uId"=>$value["uId"],"cust_id"=>$value["cust_id"]));
		}

		//array_push($array,$ar);

		$this->model_conflict->updateCustUser(array("line_prefix"=>json_encode($array)),array("uId"=>$user_id,"cust_id"=>$cust_id));
		$this->model_history->insert(array("his_action"=>"Thêm ngành hàng: ".json_encode($array),"his_create_date"=>time(),"hist_desc"=>"","user_active_id"=>$this->session->userdata('uId'),"user_id"=>$user_id,"cust_id"=>$cust_id,"his_type"=>3));
		echo json_encode(array("st"=>1,"msg"=>"Cập nhật thành công"));	

	}
}

